package wangm.util;

import wangm.bean.User;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.UUID;

import static wangm.constant.Constant.SYSTEM.LOGIN_USER;

/**
 * system util
 *
 * @author zk
 * @date 2018-02-24 18:57
 */
public class SystemUtil {

    /**
     * sha256加密算法
     *
     * @param str str
     * @return encode str
     */
    public static String enSHA256(String str){
        MessageDigest messageDigest;
        String encodeStr = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(Charset.forName("UTF-8")));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     *2 to 16
     *
     * @param bytes byte to hex
     * @return
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static User getUser(HttpServletRequest request){
        return (User) request.getAttribute(LOGIN_USER);
    }
}
